express = require 'express'
config = require './config'
gzippo = require 'gzippo'
logger = require('log4js').getLogger()
cluster = require 'cluster'
redisClient = require './models/redis_client'
connectRedis = require('connect-redis') express

cpuTotal = require('os').cpus().length

importFiles = require './helpers/import_files'

if cluster.isMaster
  for i in [1..4]
    cluster.fork()
  cluster.on 'exit', (worker, code, signal) ->
    console.log "worker #{worker.pid} died"
else
  app = express.createServer()
  #session store
  redisStore = new connectRedis {
    client : redisClient
  }


  #config
  app.configure () ->
    app.set 'view', "#{__dirname}/views"
    app.set 'view engine', 'jade'
    app.use express.bodyParser()
    app.use express.cookieParser()
    app.use express.session {
      key : config.session.key
      secret : config.session.secret
      store : redisStore
    }
    app.use express.methodOverride()
    app.use app.router
    app.use gzippo.staticGzip "#{__dirname}/public"

  app.configure 'production', () ->
    app.use express.errorHandler()

  app.configure 'development', () ->
    app.use express.errorHandler {
      dumpExceptions : true
      showStack : true
    }
    process.on 'uncaughtException', (err) ->
      logger.error "uncaughtException:#{err}"


  #routes
  require('./routes')(app)

  logger.info "config.server.port:#{config.server.port}"
  app.listen config.server.port
  logger.info "express linsten on port %d in %s mode", app.address().port, app.settings.env
